//
//  WKDiscountCouponController.m
//  WeKeTang
//
//  Created by ichina on 2017/8/31.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKDiscountCouponController.h"
#import "WKWebViewController.h"
#import "WKExpiredCouponsController.h"
#import "WKNetworkTools.h"
#import "WKUniversal.h"
#import "WKLoginHandel.h"
#import "WKUseRulesCell.h"
#import "WKDiscountCouponModel.h"

#define useRulesUrl   @"http://weixin.dezhi.com/dezhi/hongbaorules.php"

@interface WKDiscountCouponController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIButton *btnUseRules;

@property (weak, nonatomic) IBOutlet UITableView *mainTableView;

@property (nonatomic, strong) UIButton *checkBtn;

@property (nonatomic, strong) YYLabel *bottomLabel;

@property (nonatomic, strong) UIImageView *bgImageView;

@property (nonatomic, strong) NSArray *dataList;//不过期

@property (nonatomic, strong) NSArray *expireList;//过期

@end

@implementation WKDiscountCouponController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navItem.title = @"优惠券";

    [self loadDiscountCouponData];
    
    [self setupUI];
}
- (void)loadDiscountCouponData{
    
    __weak typeof(self) weakSelf = self;
    NSString *userid = [WKLoginHandel getLoginDataWithString:@"userid"];
    NSString *sessid = [WKLoginHandel getLoginDataWithString:@"SESSID"];
    NSString *mac = [WKUniversal macaddress];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"wkcouponlist" forKey:@"commandid"];
    [para setObject:userid forKey:@"userid"];
    [para setObject:mac forKey:@"mac"];
    [para setObject:sessid forKey:@"phpsessid"];
    [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"获取中..." completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSLog(@"优惠券：%@",dict);
        NSDictionary *headDict = dict[@"head"];
        NSString *statuscode = headDict[@"statuscode"];
        NSArray *bodyList = dict[@"body"];
        
        NSString * hostdateStr = [WKLoginHandel getLoginDataWithString:@"hostdate"];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate *hostdate = [dateFormatter dateFromString:hostdateStr];
       
//        NSString *msg = headDict[@"message"];
        if ([statuscode intValue] == 100) {
            self.btnUseRules.hidden = NO;
            self.checkBtn.hidden =NO;
            self.bottomLabel.hidden = NO;
            NSMutableArray *mArry = [NSMutableArray arrayWithCapacity:bodyList.count];
            NSMutableArray *expireArry = [NSMutableArray arrayWithCapacity:bodyList.count];
            for (NSInteger i = 0; i<bodyList.count; i++) {
                WKDiscountCouponModel *model = [WKDiscountCouponModel mj_objectWithKeyValues:bodyList[i]];
                NSDate *expireDate = [dateFormatter dateFromString:model.expiretime];
                //比较时间
                NSInteger index = [weakSelf compareOneDay:hostdate withAnotherDay:expireDate];
                if (index == 1) {
                    //过期
                    [expireArry addObject:model];
                }else{
                    //没过期
                    [mArry addObject:model];
                }
            }
            weakSelf.dataList = mArry.mutableCopy;
            weakSelf.expireList = expireArry.mutableCopy;
            [weakSelf.mainTableView reloadData];
        }else if([statuscode intValue] == 999){
            self.mainTableView.hidden = YES;
            self.btnUseRules.hidden = YES;
            self.bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 88, 103)];
            self.bgImageView.center = self.view.center;
            self.bgImageView.image = IMG(@"icon_youhuiquan");
            [self.view addSubview:self.bgImageView];
            
        }
    }];
    
}
- (void)setupUI{
    
    self.navgationBar.barTintColor = RGBColor(40, 188, 203);
    
    self.statusbar.backgroundColor = RGBColor(40, 188, 203);
    
    [self middleTitleColor:[UIColor whiteColor]];
    
    self.view.backgroundColor = RGBColor(245, 245, 245);
    
    [self setLeftButtonWithImage:@"icon_return_white" highlightedImage:@"icon_return_white" target:self action:@selector(backAction)];
    
    [self.btnUseRules setImageEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    
    [self.btnUseRules setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -10)];

    [self.mainTableView registerNib:[UINib nibWithNibName:@"WKUseRulesCell" bundle:nil] forCellReuseIdentifier:@"UseRulesCell"];
    
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kDeviceScreenWidth, 100)];

    self.checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.checkBtn.frame =CGRectMake(kDeviceScreenWidth - 140, 15, 140, 21);
    self.checkBtn.hidden = YES;
    [self.checkBtn setTitle:@"查看过期优惠券" forState:UIControlStateNormal];
    [self.checkBtn setTitleColor:RGBColor(44, 186, 203) forState:UIControlStateNormal];
    [self.checkBtn addTarget:self action:@selector(checkBtnAction) forControlEvents:UIControlEventTouchUpInside];
    self.checkBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [footView addSubview:self.checkBtn];
    self.bottomLabel = [[YYLabel alloc]initWithFrame:CGRectMake(0, 100 - 31, kDeviceScreenWidth, 21)];
    self.bottomLabel.textAlignment = NSTextAlignmentCenter;
    self.bottomLabel.textColor = [UIColor colorWithHexString:@"#666666"];
    self.bottomLabel.font = [UIFont systemFontOfSize:12];
    self.bottomLabel.hidden = YES;
    self.bottomLabel.text = @"已加载全部内容";
    [footView addSubview:self.bottomLabel];
    self.mainTableView.tableFooterView = footView;
}
#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static  NSString *cellIdentifier = @"UseRulesCell";
    WKUseRulesCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
      [tableView registerNib:[UINib nibWithNibName:@"WKUseRulesCell" bundle:nil] forCellReuseIdentifier:@"UseRulesCell"];
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = self.dataList[indexPath.row];
    
    return cell;
}
#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 100;
}
#pragma mark - 使用规则
- (IBAction)useRulesAction:(UIButton *)sender {
    
    WKWebViewController *webVC = [[WKWebViewController alloc]init];
    webVC.urlStr = useRulesUrl;
    webVC.isCollection = YES;
    [self.navigationController pushViewController:webVC animated:YES];
    
}
#pragma mark - 查看过期优惠券
- (void)checkBtnAction{
    
    WKExpiredCouponsController *expiredVC = [[WKExpiredCouponsController alloc]init];
    expiredVC.dataList = self.expireList;
    [self.navigationController pushViewController:expiredVC animated:YES];
    
}
//比较时间方法
- (NSInteger)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    
    if (result == NSOrderedDescending) {
        //在指定时间前面 过了指定时间 过期
        return 1;
    }
    else if (result == NSOrderedAscending){
        //没过指定时间 没过期
        return -1;
    }
    //刚好时间一样.
    return 0;
}

#pragma mark - 返回
- (void)backAction:(UIButton*)sender{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
